﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RN.ERP.Web.OrderService;
using RN.ERP.Web.ModelService;
using Newtonsoft.Json;
using Telerik.Web.UI;
using RN.ERP.Web.EnterpriseService;
using Fly.Common.Linq;
using RN.ERP.Web.BasicService;

namespace RN.ERP.Web.CA
{
    public partial class CAOrderInvoice : BasePage
    {
        OrderServiceClient client = new OrderServiceClient();
        EnterpriseServiceClient enterpriseClient = new EnterpriseServiceClient();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string t = Request.QueryString["t"];
                if (t != null && t == "1")
                {
                    InitializeWhenView();//浏览
                }
                else
                {
                    InitializeWhenAdd();//添加
                }
                //List<QueryCompanyInfoCondition> list = new List<QueryCompanyInfoCondition>();
                //QueryCompanyInfoCondition condition = new QueryCompanyInfoCondition();
                //condition.CorpUserGuid = new ParameterValue<Guid>() { O = OptEnum.Equal, V = Guid.Parse(UserInfo.CorpUserGuid) };
                //list.Add(condition);
                //var corp = JsonConvert.DeserializeObject<CompanyInfo>(enterpriseClient.GetCompanyBisicInfo(JsonConvert.SerializeObject(list), UserInfo.CurrentArea));
                if (UserInfo.RoleType == "Manager")
                {
                    RegularExpressionValidator1.Enabled = RequiredFieldValidator9.Enabled = RequiredFieldValidator10.Enabled
                        = RequiredFieldValidator11.Enabled = false;
                }
                hidRole.Value = UserInfo.RoleType;
                var corp = JsonConvert.DeserializeObject<CompanyInfo>(enterpriseClient.GetCorpInfo(UserInfo.CorpUserGuid,
                    UserInfo.CurrentArea));
                if (corp != null)
                {
                    lbAddress.Text = corp.Address;
                }
            }
        }

        private void InitializeWhenAdd()
        {
            lbtnConfirm.Enabled = true;
            string o = Request.QueryString["o"];
            hdnOrderIds.Value = o.TrimEnd(',');
            string[] orderIds = o.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            if (orderIds.Length > 0)
            {
                BindData(orderIds);
            }
        }

        private void InitializeWhenView()
        {
            ddlOptType.Enabled = false;
            ddlType.Enabled = false;
            txtTaxCode.Enabled = false;
            txtBankName.Enabled = false;
            txtBankCode.Enabled = false;
            txtTitle.Enabled = false;
            txtLinkMan.Enabled = false;
            txtTel.Enabled = false;
            txtMobile.Enabled = false;
            txtPostCode.Enabled = false;
            ddlSendType.Enabled = false;
            ddlInvoiceTitle.Enabled = false;
            txtAddress.Enabled = false;
            txtNotice.Enabled = false;
            lbtnConfirm.Enabled = false;
            string o = Request.QueryString["o"];
            BindData(o);
        }

        private void BindData(string invoiceGuid)
        {
            //查看
            Guid iGuid = Guid.Empty;
            if (Guid.TryParse(invoiceGuid, out iGuid))
            {
                List<QueryInvoiceInfoCondition> queryList = new List<QueryInvoiceInfoCondition>();
                queryList.Add(new QueryInvoiceInfoCondition()
                {
                    InvoiceGUID = new Fly.Common.Linq.ParameterValue<Guid>() { V = iGuid, O = Fly.Common.Linq.OptEnum.Equal }
                });
                List<ModelService.CaPayRelation> result = JsonConvert.DeserializeObject<List<ModelService.CaPayRelation>>(client.GetOrders(JsonConvert.SerializeObject(queryList), Guid.Parse(UserInfo.CorpUserGuid), 0, 0));
                ddlOptType.SelectedValue = result[0].InvoiceOptType.ToString();
                ddlType.SelectedValue = result[0].InvoiceType.ToString();
                txtTaxCode.Text = result[0].TaxCode;
                txtBankName.Text = result[0].BankName;
                txtBankCode.Text = result[0].BankCode;
                txtNotice.Text = result[0].Notice;
                txtTitle.Text = result[0].InvoiceTitle;
                txtTel.Text = result[0].InvoiceTel;
                txtMobile.Text = result[0].InvoiceMtel;
                txtLinkMan.Text = result[0].InvoiceLinkMan;
                txtAddress.Text = result[0].InvoiceSendAddress;
                txtPostCode.Text = result[0].InvoicePsCode;
                lbSum.Text = result[0].InvoiceSumPay == null ? string.Empty : result[0].InvoiceSumPay.ToString();
                ddlSendType.SelectedValue = result[0].SendType.ToString();
                ddlInvoiceTitle.SelectedValue = result[0].InvoiceContent.ToString();
                RadGrid1.DataSource = result;
                RadGrid1.DataBind();
            }
        }

        private void BindData(string[] orderIds)
        {
            //添加
            List<QueryInvoiceInfoCondition> queryList = new List<QueryInvoiceInfoCondition>();
            foreach (string orderId in orderIds)
            {
                int id = 0;
                if (int.TryParse(orderId, out id))
                {
                    queryList.Add(new QueryInvoiceInfoCondition()
                    {
                        ID = new Fly.Common.Linq.ParameterValue<int>()
                        {
                            V = id,
                            O = Fly.Common.Linq.OptEnum.Equal
                        }
                    });
                }
            }
            //List<ModelService.CaPayRelation> result = JsonConvert.DeserializeObject<List<ModelService.CaPayRelation>>(client.GetInvoicesList(JsonConvert.SerializeObject(queryList), 0, 0));
            List<ModelService.CaPayRelation> result = JsonConvert.DeserializeObject<List<ModelService.CaPayRelation>>(client.GetOrders(JsonConvert.SerializeObject(queryList), Guid.Parse(UserInfo.CorpUserGuid), 0, 0));

            txtTitle.Text = result[0].iTitle;
            txtTel.Text = result[0].officeTel;
            txtMobile.Text = result[0].mobileTel;
            txtLinkMan.Text = result[0].LinkPerson;
            txtAddress.Text = result[0].SendAddress;
            txtPostCode.Text = result[0].postcode;
            double? pay = result.Sum(r => r.SumPay);
            if (pay != null)
            {
                lbSum.Text = pay.ToString();
            }
            RadGrid1.DataSource = result;
            RadGrid1.DataBind();
        }

        protected void lbtnConfirm_Click(object sender, EventArgs e)
        {
            decimal sumPay = 0;
            decimal.TryParse(lbSum.Text, out sumPay);
            InvoiceOrderRelation item = new InvoiceOrderRelation()
            {
                InvoiceDate = DateTime.Now,
                IsrtDate = DateTime.Now,
                IsrtUser = UserInfo.CorpUserGuid,
                IsrtUserName = UserInfo.UserName,
                KeyGuid = Guid.NewGuid(),
                LinkMan = txtLinkMan.Text.Trim(),
                Mtel = txtMobile.Text.Trim(),
                Tel = txtTel.Text.Trim(),
                Title = txtTitle.Text.Trim(),
                SumPay = sumPay,
                SendAddress = txtAddress.Text.Trim(),
                PsCode = txtPostCode.Text.Trim(),
                Notice = txtNotice.Text.Trim(),
                OrderIds = hdnOrderIds.Value,
                SendType = int.Parse(ddlSendType.SelectedValue),
                IsDel = false,
                InvoiceStatus = 0,
                InvoiceTitle = ddlInvoiceTitle.SelectedValue,
                InvoiceOptType = byte.Parse(ddlOptType.SelectedValue),
                InvoiceType = byte.Parse(ddlType.SelectedValue)
            };
            if (tr1.Visible == true)
            {
                item.TaxCode = txtTaxCode.Text;
                item.BankName = txtBankName.Text;
                item.BankCode = txtBankCode.Text;
            }
            OperationResult result = JsonConvert.DeserializeObject<OperationResult>(client.AddInvoices(JsonConvert.SerializeObject(item)));
            if (result.Result)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "$.ligerDialog.warn('" + result.Message + "','',CloseWin);", true);
                //RadWindowManager1.RadAlert(result.Message, 300, 150, "提示", "CloseWin", "");
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "$.ligerDialog.warn('" + result.Message + "');", true);
                //RadWindowManager1.RadAlert(result.Message, 300, 150, "提示", "", "");
            }
        }
    }
}